home *** CD-ROM | disk | FTP | other *** search
/ Freelog 100 / FreelogNo100-NovembreDecembre2010.iso / Musique / solfege / solfege-win32-3.17.0.exe / {app} / bin / Lib / glob.py < prev    next >
Text File  |  2007-04-04  |  2KB  |  75 lines

  1. """Filename globbing utility."""
  2.  
  3. import os
  4. import fnmatch
  5. import re
  6.  
  7. __all__ = ["glob", "iglob"]
  8.  
  9. def glob(pathname):
  10.     """Return a list of paths matching a pathname pattern.
  11.  
  12.     The pattern may contain simple shell-style wildcards a la fnmatch.
  13.  
  14.     """
  15.     return list(iglob(pathname))
  16.  
  17. def iglob(pathname):
  18.     """Return a list of paths matching a pathname pattern.
  19.  
  20.     The pattern may contain simple shell-style wildcards a la fnmatch.
  21.  
  22.     """
  23.     if not has_magic(pathname):
  24.         if os.path.lexists(pathname):
  25.             yield pathname
  26.         return
  27.     dirname, basename = os.path.split(pathname)
  28.     if not dirname:
  29.         for name in glob1(os.curdir, basename):
  30.             yield name
  31.         return
  32.     if has_magic(dirname):
  33.         dirs = iglob(dirname)
  34.     else:
  35.         dirs = [dirname]
  36.     if has_magic(basename):
  37.         glob_in_dir = glob1
  38.     else:
  39.         glob_in_dir = glob0
  40.     for dirname in dirs:
  41.         for name in glob_in_dir(dirname, basename):
  42.             yield os.path.join(dirname, name)
  43.  
  44. # These 2 helper functions non-recursively glob inside a literal directory.
  45. # They return a list of basenames. `glob1` accepts a pattern while `glob0`
  46. # takes a literal basename (so it only has to check for its existence).
  47.  
  48. def glob1(dirname, pattern):
  49.     if not dirname:
  50.         dirname = os.curdir
  51.     try:
  52.         names = os.listdir(dirname)
  53.     except os.error:
  54.         return []
  55.     if pattern[0]!='.':
  56.         names=filter(lambda x: x[0]!='.',names)
  57.     return fnmatch.filter(names,pattern)
  58.  
  59. def glob0(dirname, basename):
  60.     if basename == '':
  61.         # `os.path.split()` returns an empty basename for paths ending with a
  62.         # directory separator.  'q*x/' should match only directories.
  63.         if os.path.isdir(dirname):
  64.             return [basename]
  65.     else:
  66.         if os.path.lexists(os.path.join(dirname, basename)):
  67.             return [basename]
  68.     return []
  69.  
  70.  
  71. magic_check = re.compile('[*?[]')
  72.  
  73. def has_magic(s):
  74.     return magic_check.search(s) is not None
  75.